package com.cloud.lawcase.api.service.impl;

import java.util.Date;
import java.util.List;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.cloud.lawcase.api.bean.ApiInterBean;
import com.cloud.lawcase.api.bean.LawApiSearchCriteria;
import com.cloud.lawcase.api.constant.LawApiEnum;
import com.cloud.lawcase.api.entity.TcAccessGlobalParams;
import com.cloud.lawcase.api.entity.TcAccessToken;
import com.cloud.lawcase.api.entity.TcAccesssInterface;
import com.cloud.lawcase.api.entity.TcRelTokenInterface;
import com.cloud.lawcase.api.mapper.TcAccessGlobalParamsMapper;
import com.cloud.lawcase.api.mapper.TcAccessTokenMapper;
import com.cloud.lawcase.api.mapper.TcAccesssInterfaceMapper;
import com.cloud.lawcase.api.mapper.TcRelTokenInterfaceMapper;
import com.cloud.lawcase.api.service.LawApiManagerService;
import com.cloud.lawcase.common.utils.DateHelper;
import com.cloud.lawcase.common.utils.RedisKeyHelper;
import com.cloud.lawcase.common.utils.UUIDHelper;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;

import tk.mybatis.mapper.entity.Example;

@Service
@Transactional
public class LawApiManagerServiceImpl implements LawApiManagerService {

	@Autowired
	private TcAccessTokenMapper tcAccessTokenMapper;

	@Autowired
	private TcAccesssInterfaceMapper tcAccesssInterfaceMapper;

	@Autowired
	private TcRelTokenInterfaceMapper tcRelTokenInterfaceMapper;

	@Autowired
	private TcAccessGlobalParamsMapper tcAccessGlobalParamsMapper;

	@Autowired
	private JdbcTemplate jdbcTemplate;

	@Override
	public PageInfo<TcAccessToken> listPage(LawApiSearchCriteria searchCriteria) {
		return PageHelper.startPage(searchCriteria.getPageNum(), searchCriteria.getPageSize()).doSelectPageInfo(() -> {
			Example example = new Example(TcAccessToken.class);
			Example.Criteria criteria = example.createCriteria();
			if (!StringUtils.isEmpty(searchCriteria.getAppId())) {
				criteria.andLike("appId", "%" + searchCriteria.getAppId() + "%");
			}
			if (!StringUtils.isEmpty(searchCriteria.getDockUnit())) {
				criteria.andLike("dockUnit", "%" + searchCriteria.getDockUnit() + "%");
			}
			if (searchCriteria.getState() > 0) {
				criteria.andEqualTo("stateId", searchCriteria.getState());
			}
			example.orderBy("createTime").desc();
			tcAccessTokenMapper.selectByExample(example);
		});
	}

	@Override
	public String delete(String appId) {
		Example example = new Example(TcRelTokenInterface.class);
		Example.Criteria criteria = example.createCriteria();
		criteria.andEqualTo("appId", appId);
		tcRelTokenInterfaceMapper.deleteByExample(example);
		tcAccessTokenMapper.deleteByPrimaryKey(appId);
		return appId;
	}

	@Override
	public TcAccessToken load(String appId) {
		return tcAccessTokenMapper.selectByPrimaryKey(appId);
	}

	@Override
	public TcAccessToken saveUpdate(TcAccessToken token) {
		if (StringUtils.isEmpty(token.getAppId())) {
			Date now = new Date();
			String appId = UUIDHelper.generateUUID();
			token.setAppId(appId);
			token.setCreateTime(now);
			token.setUpdateTime(now);
			initAppToken(token);
			tcAccessTokenMapper.insert(token);
			// 默认赋予全部接口权限
			jdbcTemplate.execute(
					"insert into tc_rel_token_interface select '" + appId + "', inter_id from tc_accesss_interface");
		} else {
			token.setUpdateTime(new Date());
			initAppToken(token);
			tcAccessTokenMapper.updateByPrimaryKey(token);
		}
		return token;
	}

	private void initAppToken(TcAccessToken token) {
		Date now = new Date();
		if (token.getOverdueDate() != null) {
			Date remindDate = DateHelper.getDateBeforeOrAfterDays(token.getOverdueDate(), -token.getOverdueRemind());
			if (now.before(token.getEnableDate())) {
				// 启用时间早于当前时间，未启用状态
				token.setStateId(LawApiEnum.UNABLE.getStateId());
				token.setStateName(LawApiEnum.UNABLE.getStateName());
			} else if (now.after(token.getEnableDate()) && now.before(remindDate)) {
				// 当前时间大于开始时间，小于预期提醒时间，狀態爲正常
				token.setStateId(LawApiEnum.NORMAL.getStateId());
				token.setStateName(LawApiEnum.NORMAL.getStateName());
			} else if (now.before(token.getOverdueDate()) && now.after(remindDate)) {
				// 当前时间晚于截止时间，并且大于提醒时间，状态为逾期提醒
				token.setStateId(LawApiEnum.REMIND.getStateId());
				token.setStateName(LawApiEnum.REMIND.getStateName());
			} else if (token.getOverdueDate().before(now)) {
				// 当前时间晚于过期时间，状态为过期
				token.setStateId(LawApiEnum.OVERDUE.getStateId());
				token.setStateName(LawApiEnum.OVERDUE.getStateName());
			}
		}
	}

	@Override
	public boolean checkUrlAuthority(String appId, String requestURI) {
		int c = jdbcTemplate.queryForObject(
				"select count(*) from tc_accesss_interface t1, tc_rel_token_interface t2 where t2.app_id = ? and t1.request_url = ? and t1.inter_id = t2.inter_id",
				Integer.class, appId, requestURI);
		return c > 0;
	}

	@Override
	public List<TcAccesssInterface> listAllInters() {
		return tcAccesssInterfaceMapper.selectAll();
	}

	@Override
	public List<TcRelTokenInterface> listCheckedInters(String appid) {
		Example example = new Example(TcRelTokenInterface.class);
		Example.Criteria criteria = example.createCriteria();
		criteria.andEqualTo("appId", appid);
		return tcRelTokenInterfaceMapper.selectByExample(example);
	}

	@Override
	public void saveUpdateInterRel(ApiInterBean apiInter) {
		// 保存可以查看的区划信息
		Example paramExample = new Example(TcAccessGlobalParams.class);
		Example.Criteria criteria = paramExample.createCriteria();
		criteria.andEqualTo("appId", apiInter.getAppId());
		tcAccessGlobalParamsMapper.deleteByExample(paramExample);
		if (apiInter.getRegions() != null && apiInter.getRegions().length > 0) {
			TcAccessGlobalParams param = new TcAccessGlobalParams();
			param.setId(RedisKeyHelper.genereateKey(TcAccessGlobalParams.class));
			param.setAppId(apiInter.getAppId());
			param.setParamName("law_region_id");
			param.setParamValue(StringUtils.join(apiInter.getRegions(), ","));
			tcAccessGlobalParamsMapper.insert(param);
		}
		// 保存关联关系信息
		Example relExample = new Example(TcRelTokenInterface.class);
		Example.Criteria relCriteria = relExample.createCriteria();
		relCriteria.andEqualTo("appId", apiInter.getAppId());
		tcRelTokenInterfaceMapper.deleteByExample(paramExample);
		for (Integer i : apiInter.getInterIds()) {
			TcRelTokenInterface interf = new TcRelTokenInterface();
			interf.setAppId(apiInter.getAppId());
			interf.setInterId(i);
			tcRelTokenInterfaceMapper.insert(interf);
		}
	}

	@Override
	public List<TcAccessGlobalParams> listGlobalParams(String appId) {
		Example example = new Example(TcAccessGlobalParams.class);
		Example.Criteria criteria = example.createCriteria();
		criteria.andEqualTo("appId", appId);
		return tcAccessGlobalParamsMapper.selectByExample(example);
	}
}
